<template>
    <div class="addAdult">
        <div class="add_item" @click="openForm">申请充值</div>
        <!-- 申请充值 -->
        <div class="dialog_from">
            <el-dialog title="申请充值页面" width='70%' :modal=false :visible.sync="outerVisible">
                <el-row style="margin:16px 0;">
                    <el-button type="danger" @click='changeApply("")' plain>申请充值</el-button>
                </el-row>
                <el-table
                    v-loading="loading"
                    element-loading-text="加载中..."
                    :data="studentsData"
                    stripe 
                    size="mini"
                    border resizable
                    style="width: 150%"
                    max-height="656">
                    <el-table-column label="订单号" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.trade_sn}} </template>
                    </el-table-column>
                    <el-table-column label="充值类型" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.payTypeAttributeName}}</template>
                    </el-table-column>
                    <el-table-column label="付费方式" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.rechargeMethodAttributeName}}</template>
                    </el-table-column>
                    <el-table-column label="产品类型" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.productname}}</template>
                    </el-table-column>
                    <el-table-column label="原价" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.totalmoney}}</template>
                    </el-table-column>
                    <el-table-column label="实付金额" :align="align" :width="columWidth">
                        <template slot-scope="scope" >{{scope.row.totalAmount}}</template>
                    </el-table-column>
                    <el-table-column label="有效期" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.duedate}}</template>
                    </el-table-column>
                    <el-table-column label="状态" :align="align" :width="columWidth">
                        <template slot-scope="scope" >
                            <span :class="scope.row.status=='error'?'highlightRed':''">{{scope.row.status | statusJudge}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="申请时间" :align="align" :width="columWidth">
                        <template slot-scope="scope">{{scope.row.addTime | transData}}</template>
                    </el-table-column>

                    <el-table-column 
                        fixed="right" 
                        :align="align"
                        min-width="198"
                        :data="studentsData"
                        label="操作">
                        <template slot-scope="scope">
                            <!-- v-if='scope.row.status=="waitting"?false:true' -->
                            <el-button
                                size="mini" plain
                                v-if='scope.row.status=="error"'
                                :type="scope.row.status=='error'?'danger':''"
                                @click='changeApply(scope.row.trade_sn,scope.row.status)'>修改申请</el-button>
                            <el-button
                                size="mini"
                                type="info" plain
                                @click='delApply(scope.row.trade_sn)'>删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div slot="footer" class="dialog-footer">
                    <el-button class="dialog_close" @click="outerVisible = false">取 消</el-button>
                    <el-button class="dialog_confirm" type="primary" @click="outerVisible = false">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <!-- 申请、修改充值付费 -->
        <el-dialog title="申请充值付费" :modal=false :close-on-click-modal=false :visible.sync="dialogformVisible1">
            <div class="tipstyleH" v-if='wrongTipShow'>审核不通过原因:{{wrongTip}}</div>
            <el-form :model="form" >
                <div class="center_title">{{dialogTitle}}</div>
                <el-form-item label="学员姓名："  :label-width="formLabelWidth">
                    <el-input v-model="studentName" disabled class="divided_2"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="学员账号：" :label-width="formLabelWidth">
                    <el-input v-model="studentPhone" disabled class="divided_2"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="充值类型：" :label-width="formLabelWidth">
                    <el-select v-model="recharge1" @change="recharge1Change" class="divided_150">
                        <el-option v-for='(recharge,j) in rechargeList'
                            :key="j"
                            :label="recharge.attriname"
                            :value="recharge.attriid"></el-option>
                    </el-select>
                    <el-select v-model="recharge2" v-if='inRecharge' @change="recharge2Change" class="divided_150">
                        <el-option v-for='(recharge2,m) in rechargeList2'
                            :key="m"
                            :label="recharge2.attriname"
                            :value="recharge2.attriid"></el-option>
                    </el-select>
                    <el-button style="margin-left:40px;" @click="addProduct(false)" size='small'>增加产品</el-button>
                    <el-button size='small' @click="addProduct(true)">随单赠送</el-button>
                    <el-button size='small' @click="calculatePrice">计算</el-button>
                </el-form-item>
                <!-- v-if='boxCardExit' -->
                <el-card class="box-card">
                    <p class="tipstyle">学员付费信息（此处填写学员课时付款的相关信息，而非学校购买次卡的付款信息）</p>
                    <el-form-item label="付费方式：" :label-width="formLabelWidth">
                        <el-select v-model="paymentMethod" :disabled="boxCardGrey">
                            <el-option v-for='(payt,k) in payTypeList'
                            :key="k"
                            :label="payt.attriname"
                            :value="payt.attriid"></el-option> 
                        </el-select>
                    </el-form-item> 
                    <el-form-item label="付款金额：" :label-width="formLabelWidth">
                        <el-input v-model="totalAmount" :disabled="boxCardGrey" class="divided_2"  auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="订单/交易流水号：" :label-width="formLabelWidth">
                        <el-input v-model="orderSn" :disabled="boxCardGrey" class="divided_2"  auto-complete="off"></el-input>
                    </el-form-item> 
                </el-card>
                <el-card class="box-card" v-for='(card,index) in product' :key='index' >
                    <div slot="header" class="clearfix">
                        <el-button @click="removeProduct(index)" class="closeIcon" icon='el-icon-close' type="text"></el-button>
                    </div>
                    <div class="text item" style="margin: 6px 0;padding: 10px 0 1px 0;">
                        <el-form-item label="充值类型：" v-if='card.suidan' :label-width="formLabelWidth">
                            <el-select v-model="card.payType1" disabled class="divided_150">
                                <el-option label="赠送"
                                    value="1875"></el-option>
                            </el-select>
                            <el-select v-model="card.payType2" disabled class="divided_150">
                                <el-option label="随单赠送"
                                    value="1978"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="产品类型：" :label-width="formLabelWidth">
                            <el-select v-model="card.productId" @change="selectGet">
                                <el-option v-for='(pro,i) in productList'
                                    :key="i"
                                    :label="pro.productname"
                                    :value="pro.productid"></el-option>
                            </el-select>
                        </el-form-item> 
                        <el-form-item label="数量：" :label-width="formLabelWidth">
                            <el-input v-model="card.quantity" class="divided_2"  auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="系统计算价格：" :label-width="formLabelWidth">
                            <el-input v-model="card.money" disabled placeholder="自动计算" class="divided_2"  auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="实际付费金额：" :label-width="formLabelWidth">
                            <el-input v-model="card.actrualmoney" class="divided_2"  auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="充值有效期：" placeholder="不填则系统自动计算" :label-width="formLabelWidth">
                            <el-input v-model="card.duedate" disabled class="divided_2"  auto-complete="off" placeholder='不填则系统自动计算'></el-input>
                        </el-form-item> 
                    </div>
                </el-card>
                <el-form-item label="充值备注：" style="margin-top:10px;" :label-width="formLabelWidth">
                    <el-input v-model="remark" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button class="dialog_close" @click="cancelAndClear">取 消</el-button>
                <el-button class="dialog_confirm" type="primary" @click="confirmApply">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import base from './../../api/base.js'
import {formatDate} from './../../../static/js/date.js'
import bus from './../../../static/js/bus.js'
import Qs from 'qs'
export default {
    data() {
        // var checkPayment = (rule, value, callback) => {
        //     if (!value) {
        //         callback(new Error('付款金额不能为空'));
        //     }else if(!Number.isInteger(value)) {
        //         callback(new Error('请输入数字值'));
        //     } 
        // };
        return {
                wrongTip:'',//审核不通过文字
                wrongTipShow:false,
                dialogTitle:'申请充值付费',
                boxCardGrey:false,//课程补偿和赠送判断
                rechargeInfo:'',
                studentId:'',//申请充值
                studentName:'',
                studentPhone:'',
                payType:'',
                paymentMethod:'',
                totalAmount:'',
                orderSn:'',
                remark:'',
                product:'',
                liushui:'',
                product:[
                    {
                        productId:'',//产品ID
                        quantity:'',//数量
                        money:'',//价格
                        actrualmoney:'',//实际支付
                        duedate:'',//有效期
                        type:'',//固定充值类型
                        payType1:'',
                        payType2:'',
                        suidan:false,//非随单赠送
                    }
                ],//产品
                
                payTypeList:[],//付款方式列表
                productList:[],//产品列表

                rechargeList:[],//充值方式列表
                rechargeList2:[],
                inRecharge:false,
                recharge1:'',
                recharge2:'', 

                sendProduct:[],
                zengsong:'',//默认非赠送
                calcutedPrices:[],//计算的价格

                saleList:[],
                studentsData: [],
                loading:true,
                assitantList:'',
                saleList:'',
                outerVisible: false,
                dialogformVisible1:false,//修改申请
                dialogformVisible2:false,//删除
                // 表格
                form: {
                    name: '',
                    delivery: false,
                    name:'',
                    assitant:'',
                    saleid:'',
                    remark:'',
                },
                formLabelWidth: '140px',
                columWidth:108,
                align:'center',
        };
    },
    methods:{
        // 申请充值弹窗
        openForm(){
            if(this.studentId){
                this.outerVisible = true
                this.getData()
                this.getSaleList()
            }else{
                this.alertTip('请选择学员')
            } 
            
        },
        changeApply(tsn,status){
            this.liushui=tsn
            this.dialogformVisible1=true
            this.getRechargeInfo()
            this.getPayType()
            this.getProList()
            this.getChargeType()
            // this.clearApplyInfo()    
            if(status=='error'){
                this.dialogTitle='修改充值付费'
                this.wrongTipShow=true
            }
        },
        // 获取充值信息
        getRechargeInfo(){
            this.$axios({
                url: base.baseUrl+"/school/account/get-apply-recharge-info",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token: localStorage.token,
                    tradeSn:this.liushui
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){

                    if(res.data.data){
                        this.rechargeInfo=res.data.data
                        this.studentId=this.rechargeInfo.studentId//申请充值
                        this.studentName=this.rechargeInfo.studentName
                        this.studentPhone=this.rechargeInfo.studentPhone
                        this.payType=this.rechargeInfo.payType
                        this.paymentMethod=this.rechargeInfo.paymentMethod
                        this.totalAmount=this.rechargeInfo.totalAmount
                        this.orderSn=this.rechargeInfo.orderSn
                        this.remark=this.rechargeInfo.remark
                        this.product=this.rechargeInfo.product
                        this.liushui=this.rechargeInfo.tradeSn
                        this.product=this.rechargeInfo.product 
                        this.recharge1=this.rechargeInfo.payType
                        this.wrongTip=this.rechargeInfo.lastTrialRemark?this.rechargeInfo.lastTrialRemark:this.rechargeInfo.firstTrialRemark;
                    }
                }
            });
        },
        delApply(tsn){
            let data=Qs.stringify({
                token:localStorage.token,
                tradeSn:tsn
            })

            this.$axios({
                
                url: base.baseUrl+"/school/account/del-recharge",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },          
                data:data

            }).then(res => {
                
                this.$alert(res.data.msg)
                this.getData()
            });
        },
        // 增加产品or随单赠送
        addProduct(param){

            this.product.push({
                suidan:param,
                productId:'',//产品ID
                quantity:'',//数量
                money:'',//价格
                actrualmoney:'',//实际支付
                duedate:'',//有效期
                zengsong:param?2:1,
                payType1:'1875',
                payType2:'',
                type:param?'1978':'',
            })
           
        },
        // 移除产品
        removeProduct(index){
            this.product.splice(index,1)
        },
        // 申请充值付费取消
        cancelAndClear(){
            this.dialogformVisible1 = false
            this.clearApplyInfo()    
        },
        getData(){ 
            this.$axios({
                url: base.baseUrl+"/school/account/get-audited-recharge-list",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token: localStorage.token,
                    userId:this.studentId
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){
                    this.loading=false
                    if(res.data.data){
                        this.studentsData=res.data.data;
                    }else{
                        this.studentsData=[]
                    }
                    // this.totalCount=Number(res.data.data.pages.total_count);
                }else if(res.data.code==-2){
                    this.$router.push('/login')
                }
            });
        },
        // 获取 支付方式 
        getPayType(){ 
            this.$axios({
                url: base.baseUrl+"/school/account/get-payment-method",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token: localStorage.token
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){
                    this.payTypeList=res.data.data
                }else if(res.data.code==-2){
                    this.$router.push('/login')
                }
            });
        },
        // 获取 产品列表 
        getProList(){ 
            this.$axios({
                url: base.baseUrl+"/school/account/get-product-list",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token: localStorage.token,
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){

                    this.productList=res.data.data

                }else if(res.data.code==-2){
                    this.$router.push('/login')
                }
            });
        },
        // 获取 充值类型
        getChargeType(){
             this.$axios({
                url: base.baseUrl+"/school/account/get-pay-type-list",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token: localStorage.token
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){
                    this.rechargeList=res.data.data
                }else if(res.data.code==-2){
                    this.$router.push('/login')
                }
            });
        },
        recharge1Change(e){
            this.recharge2=''
            this.getChargeType2(e)
            // 当选择课程补偿和赠送时隐藏
            if(e=='1894'||e=='1895'){
                this.boxCardGrey=true
                this.paymentMethod='1901'
                this.totalAmount=0
                this.orderSn=0
            }else{
                this.boxCardGrey=false
                // this.paymentMethod=''
                // this.totalAmount=''
                // this.orderSn=''
            }
        },
        getChargeType2(e){
             this.$axios({
                url: base.baseUrl+"/school/account/get-pay-type-list",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token: localStorage.token,
                    payTypeId:e
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){
                    if(res.data.data){
                        this.inRecharge=true
                        this.rechargeList2=res.data.data
                    }else{
                        this.inRecharge=false
                        this.payType=this.recharge1
                    }
                }
            });
        },
        recharge2Change(e){
            this.payType=e
        },
        selectGet(vId){
            // let obj = { };
            // obj = this.productList.find((item)=>{//这里的selectList就是上面遍历的数据源
            //     return item.productid === vId;//筛选出匹配数据
            // });
            // console.log(obj.price);
           
        },
        //计算价格 
        calculatePrice(){
            // console.log(this.product)
            this.sendProduct=[]
            this.product.forEach(item=>{
                this.sendProduct.push({
                    productId:item.productId,
                    quantity:item.quantity,
                    type:item.zengsong
                })
            })
            let data=Qs.stringify({
                token:localStorage.token,
                totalPay:this.totalAmount,
                productList:this.sendProduct
            })
            this.$axios({
                
                url: base.baseUrl+"/school/account/calculating-price",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },          
                data:data

            }).then(res => {
                if(res.data.code==-1){
                     this.$alert(res.data.msg)
                }else if(res.data.code==200){
                    this.calcutedPrices=res.data.data
                    this.product.forEach((item,index)=>{
                        item.money=this.calcutedPrices[index].money
                        item.actrualmoney=this.calcutedPrices[index].actrualmoney
                        item.duedate=this.calcutedPrices[index].duedate
                    })

                }
            });
        },
        // 申请充值
        confirmApply(){
            var applyTip;
            if(localStorage.school_type=='1'||localStorage.school_type=='3'){
                applyTip='该笔充值需要提交财务审核，是否提交?'
            }else if(localStorage.school_type=='2'){
                applyTip='是否确认充值?'
            }
            this.$confirm(applyTip, {
                // distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
            .then(() => {
                this.toApplyRecharge()
            })
        },
        toApplyRecharge(){
            var product=[];
            this.product.forEach(item=>{
                product.push({
                    productId:item.productId,//产品ID
                    quantity:item.quantity,//数量
                    money:item.money,//价格
                    actrualmoney:item.actrualmoney,//实际支付
                    duedate:item.duedate,//有效期
                    type:item.type,//固定充值类型
                })
            })
            // console.log(product)
            var data = Qs.stringify({
                token: localStorage.token,
                studentId:this.studentId,
                studentName:this.studentName,
                studentPhone:this.studentPhone,
                payType:this.payType,
                paymentMethod:this.paymentMethod,
                totalAmount:this.totalAmount,
                orderSn:this.orderSn,
                remark:this.remark,
                product:product,
                tradeSn:this.liushui?this.liushui:'',
            });
            
            this.$axios({
                url: base.baseUrl+"/school/account/apply-recharge",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },          
                data:data
            }).then(res => {
                if(res.data.code==-1){
                    this.alertTip(res.data.msg)
                }else if(res.data.code==200){
                    // this.sendApply()
                    this.alertTip('充值成功')
                    this.dialogformVisible1=false
                    this.getData()
                    this.clearApplyInfo()   
                                        
                }else if(res.data.code==-2){
                    this.$router.push('/login')
                }
            });
        },
        // 清除申请信息
        clearApplyInfo(){
            this.recharge1=this.recharge2=this.paymentMethod=this.totalAmount=this.orderSn=this.remark=this.payType=''
            // this.product=[]
            this.product.length=1
            this.product[0].productId=this.product[0].quantity=this.product[0].type=this.product[0].money=this.product[0].actrualmoney=this.product[0].duedate=''
        },
        // 发送给财务审核
        sendApply(){
           
            let data=Qs.stringify({
                token:localStorage.token,
                tradeSn:this.liushui,
            })

            this.$axios({
                
                url: base.baseUrl+"/school/account/send-apply-recharge",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },          
                data:data

            }).then(res => {
                this.$alert(res.data.msg)
                if(res.data.code==200){
                    this.dialogformVisible1=false
                    // this.clearApplyInfo()    
                    this.getData()
                }
            });
        },
        getSaleList(){
            this.$axios({
                url: base.baseUrl+"/school/agent/get-role-name",
                method: "POST",
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data:{
                    token:localStorage.token,
                    role:18
                },
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
            }).then(res => {  
                if(res.data.code==200){
                    this.saleList=res.data.data
                }else if(res.data.code==-2){
                    this.$router.push('/login');
                }
            });
        },
        alertTip(msg){
            this.$alert(msg, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    // this.$message({
                    //     type: 'info',
                    // });
                }
            });
        }
    },
    filters:{  
        transData(time){
            return formatDate(new Date(time * 1000), 'yyyy-MM-dd hh:mm');
        },
        statusJudge(stutas){
            switch(stutas){
                case 'waitting':
                    return '等待初审审核'
                    break;
                case 'error':
                    return '重新修改'
                    break;
                case 'succ':
                    return '审核成功'
                    break;
                case 'progress':
                    return '等待终审'
                    break;
            }
        },
        reEditJudge(status){
            if(status=='waitting'||status=='progress'){
                return false;
            }else{
                return true;
            }
        }
    },
    mounted(){
        bus.$on('sendstuid',(msg)=>{
            this.studentId=msg.userid
            this.studentName=msg.nickname
            this.studentPhone=msg.username
        })
    }
};
</script>
<style lang="less" scoped>
    .box-card{
        margin-bottom: 10px;
    }
    .highlightRed{
        color: red;
    }
    
    .addAdult{
        .shadow{
            -webkit-box-shadow: #666 0px 0px 10px;
            -moz-box-shadow: #666 0px 0px 10px;
            box-shadow: #666 0px 0px 10px;
            
        }
        .tipstyle{
            text-align: center;
            color: #ff4a60;
        }
        .tipstyleH{
            .tipstyle;
            height: 30px;
        }
        .closeIcon{
            position:relative;
            left:96%;
            font-size:22px;
        }
    }
</style>

